package com.standardoperationapp.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.TimeUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.textclassifier.ConversationAction;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.standardoperationapp.R;
import com.standardoperationapp.adapter.DoorListAdapter;
import com.standardoperationapp.bean.CheckLockEmpowerBean;
import com.standardoperationapp.bean.CilckEventBean;
import com.standardoperationapp.bean.LockOpenBean;
import com.standardoperationapp.bluetooth.BleLockParamInfo;
import com.standardoperationapp.bluetooth.BluetoothManger;
import com.standardoperationapp.bluetooth.ByteConvert;
import com.standardoperationapp.bluetooth.OnBleLockStateChangedListener;
import com.standardoperationapp.global.GlobalVaries;
import com.standardoperationapp.global.GsonUtils;
import com.standardoperationapp.net.BaseSubscribe;
import com.standardoperationapp.net.OnSuccessAndFaultListener;
import com.standardoperationapp.net.OnSuccessAndFaultSub;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;

public class BluetoothSetActivity extends AppCompatActivity {

    private String TAG = "TestMsg";

    public static int counter = 0;
    public static int cur_commonid = 0;

    private Context context;


    private List<String> mPermissionList = new ArrayList<>();
    private Button keyBtn, emergencyBtn,updateBtn;
    private ListView listView;
    private List<LockOpenBean.DataItem> list = new ArrayList<LockOpenBean.DataItem>();
    private DoorListAdapter listAdapter;
    private AlertDialog.Builder alertBuilder;
    private AlertDialog alertDialog;
    private TextView batteryTv, warnTv;
    private ProgressDialog progressDialog;
    private String opentime;
    private String closetime;
    private boolean ConnectCounterFlag=false;
    private int  ConnectCounter=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_set);
        context = this;
        GlobalVaries.curBlueMac="";
        Log.e("syj","create");
        //   SharedPreferencesUtils.setSharedPreferencesData(BluetoothSetActivity.this, "token", "568702e4-3dd0-4cfd-a58d-65a6c8612529");
        keyBtn = (Button) findViewById(R.id.door_applyKeyBtn);
        emergencyBtn = (Button) findViewById(R.id.door_emergyBtn);
        updateBtn = (Button) findViewById(R.id.door_updateBtn);

        keyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GlobalVaries.uiType = GlobalVaries.DOOR_APPLY_KEY;
               // finish();
                Intent intent = new Intent(BluetoothSetActivity.this, ApplyDoorKeyActivity.class);
                startActivity(intent);
            }
        });
        emergencyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GlobalVaries.uiType = GlobalVaries.DOOR_EMERGENCY;
              //  finish();
                Intent intent = new Intent(BluetoothSetActivity.this, EmergencyDoorActivity.class);
                startActivity(intent);
            }
        });
        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.clear();
                scanBlueDevice();

            }
        });
        initListView();
   //     getDoorsInfo_test();
      //  getDoorsInfo();
      //  GlobalVaries.curBlueMac="FB:35:D2:63:BF:0B";
        //注册
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        scanBlueDevice();
//        BaseSubscribe.getLockOpenList(BluetoothSetActivity.this, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
//            @Override
//            public void onSuccess(Object result) {
//                LockOpenBean lockOpenBean = GsonUtils.fromJson(result.toString(), LockOpenBean.class);
//                //syj  仅用于0416测试
//                //    lockOpenBean.getData().get(0).setMacAddress("D0:ED:2B:46:A2:B8");
//                //    lockOpenBean.getData().get(1).setMacAddress("D0:ED:2B:46:A2:B9");
//                for (int i = 0; i < lockOpenBean.getData().size(); i++) {
//                    LockOpenBean.DataItem dataItem = lockOpenBean.getData().get(i);
//                    list.add(dataItem);
//
//                }
////list.add(lockOpenBean.getData().get(0));
//
//                if (listAdapter == null) {
//                    listAdapter = new DoorListAdapter(BluetoothSetActivity.this, list);
//                    listView.setAdapter(listAdapter);
//                } else {
//                    listAdapter.upDta(list);
//                    listAdapter.notifyDataSetChanged();
//                }
//
//            }
//
//            @Override
//            public void onFault(String errorMsg) {
//                Toast.makeText(BluetoothSetActivity.this, "获取通道锁列表失败！" + errorMsg, Toast.LENGTH_LONG).show();
//            }
//
//        }));
    }
    public void scanBlueDevice()
    {
        startShowProgressDialog("正在扫描设备，请等待");
        startBlueScan();
        // 假设我们设置扫描5秒
        Handler counterhandler = new Handler();
        counterhandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // 停止扫描
                BluetoothManger.stopScan();
                dismissprogressDialog();
                if(BluetoothManger.mbluetoothDeviceList.size()==0)
                {
                    Toast.makeText(BluetoothSetActivity.this,"没有发现蓝牙锁，请重新扫描！",Toast.LENGTH_LONG).show();
                }else {
                    getDoorsInfo();
                }
            }
        }, 30000);
    }
@Subscribe(sticky = true,threadMode = ThreadMode.MAIN)
    public void getEventBus(CilckEventBean event){
        Log.e("TAG","------------"+event.getPosition()+" "+event.getType());
       // curSelectIndex=event.getPosition();
       // type =event.getType();
        if(event.getType()==1) {
            checekInfo(event.getPosition());
        }
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if(player!=null)
        {
            if(player.isLooping()) {
                player.setLooping(false);
            }
            if(player.isPlaying()) {
                player.stop();
            }
            player.release(); // 释放资源
            player =null;
        }
    }
@Override
protected void  onStart() {
    super.onStart();
    Log.e("syj","start");

}
    private void getDoorsInfo_test() {
        String obj = " {\n" +
                "      \"id\": 9,\n" +
                "      \"lockId\": 6,\n" +
                "      \"doorName\": \"333\",\n" +
                "      \"userName\": \"test\",\n" +
                "      \"createTime\": \"2024-03-25 16:43:03\",\n" +
                "      \"leftOpenLockTime\": \"2024-03-19 14:18:52\",\n" +
                "      \"rightOpenLockTime\": \"2024-04-20 14:18:52\",\n" +
                "      \"openLockCount\": 10,\n" +
                "      \"residueOpenLockCount\": 10,\n" +
                "      \"reason\": \"111\",\n" +
                "      \"illustrate\": \"222\",\n" +
                "      \"macAddress\": \"D0:ED:2B:46:A2:B9\",\n" +
                "      \"imeiNum\": \"F102\"" +

                "    }";
      //  "      \"macAddress\": \"FB:35:D2:63:BF:0B\",\n" +
        LockOpenBean.DataItem li = GsonUtils.fromJson(obj.toString(), LockOpenBean.DataItem.class);
        list.add(li);

        listAdapter = new DoorListAdapter(this, list);
        listView.setAdapter(listAdapter);

        return;
    }

    private void initListView() {
        listView = (ListView) findViewById(R.id.door_listView);
//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//
//                View itemLayout = view;
//                TextView tv = itemLayout.findViewById(R.id.door_txt4);
//                LockOpenBean.DataItem item = (LockOpenBean.DataItem) listView.getAdapter().getItem(i);
//                GlobalVaries.curBlueMac = item.getMacAddress();
//                if(GlobalVaries.debugFlag){
//                    GlobalVaries.curBlueMac="FB:35:D2:63:BF:0B";
//                }
//                Log.e(TAG, "GlobalVaries.curBlueMac    " + GlobalVaries.curBlueMac);
//
//                tv.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
////                        ConnectCounterFlag=false;
////                        ConnectCounter =0;
////                        startBluetooth();
//                        GlobalVaries.curBlueMac = item.getMacAddress();
//                          Log.e(TAG,"CLICK2 ");
//
//                        Log.e(TAG, "GlobalVaries.curBlueMac    " + GlobalVaries.curBlueMac);
//                        if (item.getResidueOpenLockCount() <= 0) {
//                            Toast.makeText(BluetoothSetActivity.this, "剩余开锁次数不足！", Toast.LENGTH_LONG).show();
//                            return;
//                        }
//                        if (timeIsValid(item.getCreateTime(), item.getRightOpenLockTime()) == false) {
//                            Toast.makeText(BluetoothSetActivity.this, "不在授权时间范围！", Toast.LENGTH_LONG).show();
//                            return;
//                        }
//
//                        cur_commonid = item.getId();
//                        checkLockEmpower(Integer.toString(item.getId()));
//
//
//                    }
//                });
//            }
//        });
        //添加表头
        View headerView = LayoutInflater.from(this).inflate(R.layout.door_list_item, listView, false);
        listView.addHeaderView(headerView);
        TextView tx1 = headerView.findViewById(R.id.door_txt1);
        tx1.setText("通道门");
        tx1 = headerView.findViewById(R.id.door_txt2);
        tx1.setText("剩余开锁\n次数");
        tx1.setGravity(View.TEXT_ALIGNMENT_CENTER);
        tx1 = headerView.findViewById(R.id.door_txt3);
        tx1.setText("授权时间\n");
        tx1 = headerView.findViewById(R.id.door_txt4);
        tx1.setText("操作");

    }
public void checekInfo(int position){
   // LockOpenBean.DataItem item = (LockOpenBean.DataItem) listView.getAdapter().getItem(position);
    LockOpenBean.DataItem item =(LockOpenBean.DataItem) listAdapter.getItem(position);
    GlobalVaries.curBlueMac = item.getMacAddress();
   // Log.e(TAG,"CLICK2 ");

    Log.e(TAG, "GlobalVaries.curBlueMac    " + GlobalVaries.curBlueMac);
    if (item.getResidueOpenLockCount() <= 0) {
        Toast.makeText(BluetoothSetActivity.this, "剩余开锁次数不足！", Toast.LENGTH_LONG).show();
        return;
    }
    if (timeIsValid(item.getLeftOpenLockTime(), item.getRightOpenLockTime()) == false) {
        Toast.makeText(BluetoothSetActivity.this, "不在授权时间范围！", Toast.LENGTH_LONG).show();
        return;
    }

    cur_commonid = item.getId();
    checkLockEmpower(Integer.toString(item.getId()));
}
    public boolean timeIsValid(String lefttime, String righttime) {
        boolean result = false;
        SimpleDateFormat format;
        Date date = null;
        long begin_time = 0, end_time = 0, cur_time = 0;
        format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = (Date) format.parse(lefttime);
            begin_time = date.getTime();
            date = (Date) format.parse(righttime);
            end_time = date.getTime();

            cur_time = System.currentTimeMillis();
        } catch (ParseException e) {

            e.printStackTrace();
        }
        if ((begin_time <= cur_time) && (cur_time <= end_time)) {
            result = true;
        }
        return result;
    }

    public void checkLockEmpower(String id) {
        // boolean result=false;
        BaseSubscribe.checkLockEmpower(BluetoothSetActivity.this, id, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                CheckLockEmpowerBean checkLockEmpowerBean = GsonUtils.fromJson(result.toString(), CheckLockEmpowerBean.class);
                if (checkLockEmpowerBean.getCode() == 200) {
                    if(ConnectCounterFlag==true||GlobalVaries.UpdateWarnFlag==true){
                        Toast.makeText(BluetoothSetActivity.this, "请先关锁!!!！" , Toast.LENGTH_LONG).show();
return;
                    }
                    //有权限
                    ConnectCounterFlag=true;
                    ConnectCounter =0;
                    startBluetooth();
                    //     result =true;
                    // Log.e("syj","test1");
                }

            }

            @Override
            public void onFault(String errorMsg) {
                Toast.makeText(BluetoothSetActivity.this, "没有开锁授权，请申请开锁！" + errorMsg, Toast.LENGTH_LONG).show();
            }

        }));


    }

    public void startBlueScan(){
        if(BluetoothManger.isStartScan){
            Toast.makeText(BluetoothSetActivity.this,"有正在进行的蓝牙扫描，请等待",Toast.LENGTH_SHORT).show();
            return;
        }
        BluetoothManger.blueHandler =handler;

        BluetoothManger.initBluetooth(BluetoothSetActivity.this,handler,ConnectCounter);
        BluetoothManger.initPermission(BluetoothSetActivity.this);
        boolean bluetoothLEAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
        //   GlobalVaries.curBlueMac="D0:ED:2B:46:A2:B9";

        alertBuilder = null;
        if (bluetoothLEAvailable) {
            BluetoothManger.startScan();
        }

    }
    @SuppressLint("MissingPermission")
    public void startBluetooth() {

//        BluetoothManger.blueHandler =handler;
//
//        BluetoothManger.initBluetooth(BluetoothSetActivity.this,handler,ConnectCounter);
//        BluetoothManger.initPermission(BluetoothSetActivity.this);
//        boolean bluetoothLEAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
//     //   GlobalVaries.curBlueMac="D0:ED:2B:46:A2:B9";
//
//        alertBuilder = null;
//        if (bluetoothLEAvailable) {
//            //   GlobalVaries.curBlueMac="FB:35:D2:63:BF:0B";
            BluetoothManger.connectLock(BluetoothSetActivity.this,handler, GlobalVaries.curBlueMac, false);
            startShowProgressDialog("正在连接蓝牙设备！");
            ConnectCounterFlag = true;
            if(BluetoothManger.reconnectFlag==false) {
                ConnectThread connectThread = new ConnectThread();
                new Thread(connectThread).start();
            }
     //   }
    }
    public void recordOpenLock(String id) {
        HashMap<String ,String> hashMap =new HashMap<String ,String>();
        hashMap.put("battery",Integer.toString(GlobalVaries.curBattery.intValue()));
      //  hashMap.put("openTime",);
      //  hashMap.put("closeTime",);
        hashMap.put("openTime",GlobalVaries.openTime);
        hashMap.put("closeTime",GlobalVaries.closeTime);
       // Toast.makeText(BluetoothSetActivity.this, "当前发送的电量为" + Integer.toString(GlobalVaries.curBattery.intValue()), Toast.LENGTH_LONG).show();

        BaseSubscribe.getLockOpen(BluetoothSetActivity.this, id,hashMap, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                //重新刷新
                list.clear();
                getDoorsInfo();
            }

            @Override
            public void onFault(String errorMsg) {
                Toast.makeText(BluetoothSetActivity.this, "发送开锁记录失败！" + errorMsg, Toast.LENGTH_LONG).show();
            }

        }));

    }





    private void getDoorsInfo() {

        BaseSubscribe.getLockOpenList(BluetoothSetActivity.this, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                LockOpenBean lockOpenBean = GsonUtils.fromJson(result.toString(), LockOpenBean.class);
                if(lockOpenBean==null){
                    Toast.makeText(BluetoothSetActivity.this,"获取开锁列表为空！",Toast.LENGTH_LONG).show();
                     return;
                }
//                //syj  仅用于0416测试
//                lockOpenBean.getData().get(0).setMacAddress("D0:ED:2B:46:A2:B8");
//                lockOpenBean.getData().get(1).setMacAddress("D0:ED:2B:46:A2:B9");
//                lockOpenBean.getData().get(1).setRightOpenLockTime("2024-12-31 01:02:03");
            //    getBluetoothLock("1");
                boolean findlock =false;
                String bluedev="scan:";
                String recedev="rec: ";
                for (int i = 0; i < lockOpenBean.getData().size(); i++) {
                    LockOpenBean.DataItem dataItem = lockOpenBean.getData().get(i);
                    if(dataItem==null)
                    {
                        continue;
                    }
                    if(dataItem.getMacAddress()==null)
                    {
                        recedev +=("\n");
                        continue;
                    }else {
                        recedev +=(dataItem.getMacAddress()+"\n");
                    }
                    for(int j=0;j<BluetoothManger.mbluetoothDeviceList.size();j++)
                    {
                        if(i==0){
                            bluedev +=(BluetoothManger.mbluetoothDeviceList.get(j)+"\n");
                                }
                        if(dataItem.getMacAddress().equals(BluetoothManger.mbluetoothDeviceList.get(j).getAddress()))
                        {
                            if(dataItem.getOpenLockCount()>0){
                                list.add(dataItem);
                                findlock=true;
                            }

                        }
                    }

                }
                if(findlock==false){
                    Toast.makeText(BluetoothSetActivity.this,"列表中没有找到授权的蓝牙设备！\n"+recedev+bluedev,Toast.LENGTH_LONG).show();
                }
//list.add(lockOpenBean.getData().get(0));

                if (listAdapter == null) {
                    listAdapter = new DoorListAdapter(BluetoothSetActivity.this, list);
                    listView.setAdapter(listAdapter);
                } else {
                    listAdapter.upDta(list);
                    listAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onFault(String errorMsg) {
                Toast.makeText(BluetoothSetActivity.this, "获取通道锁列表失败！" + errorMsg, Toast.LENGTH_LONG).show();
            }

        }));


    }
    private void startShowProgressDialog(String msg) {
        Log.e("syj","startShowProgressDialog");
        if (progressDialog == null) {
            Log.e("syj","null");
            progressDialog = new ProgressDialog(BluetoothSetActivity.this);

            progressDialog.setTitle("提示");//设置对话框显示的内容

            progressDialog.setMessage(msg);//设置不能用“取消”按钮关闭

            progressDialog.setCancelable(false);//设置对话框的进度条风格

            progressDialog.show();

        } else {
            progressDialog.setMessage(msg);
        }


    }

    public void dismissprogressDialog() {
        Log.e("syj","dismissdialog");
        progressDialog.dismiss();
        progressDialog=null;

    }
    public void showWarnDialog(String lefttime, Double battery) {
        if (GlobalVaries.UpdateWarnFlag == false)
        {
            Log.e("syj","updateFlag false");
            return;
        }

        if (alertBuilder == null) {
            alertBuilder = new AlertDialog.Builder(this);
            final View view = getLayoutInflater().inflate(R.layout.activity_door_warn, null);

            warnTv = (TextView) view.findViewById(R.id.warn_closewarn_tx);
            warnTv.setText("关锁提醒：" + lefttime);
            batteryTv = (TextView) view.findViewById(R.id.warn_battery_tx);
            Log.e("syj","update3:"+Double.toString(GlobalVaries.curBattery));

            batteryTv.setText("门锁剩余电量： " + Integer.toString( GlobalVaries.curBattery.intValue())+"%");
            Button closeBtn = (Button) view.findViewById(R.id.warn_close_Btn);
            closeBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(BluetoothManger.mLockIsOpened)
                    {
                        Toast.makeText(BluetoothSetActivity.this, "请检查是否关锁！", Toast.LENGTH_LONG).show();
                        return ;
                    }else{
                        Toast.makeText(BluetoothSetActivity.this, "关锁", Toast.LENGTH_LONG).show();
                        GlobalVaries.UpdateWarnFlag = false;
                        BluetoothManger.counter = 0;
                        BluetoothManger.disconnectLock();

                        alertDialog.dismiss();
                        alertBuilder = null;
                    }

                }
            });
            alertBuilder.setCancelable(false);
            alertBuilder.setView(view);
//    builder.setPositiveButton("关锁", new DialogInterface.OnClickListener() {
//        @Override
//        public void onClick(DialogInterface dialog, int which) {
//
//            dialog.cancel();
//        }
//    });
            alertDialog = alertBuilder.create();

//            alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    dialog.cancel();
//                }
//            });
            alertDialog.show();
        } else {
            warnTv.setText("关锁提醒：" + lefttime);
            batteryTv.setText("门锁剩余电量： " + Integer.toString(battery.intValue())+"%");
        }

        long cur_time = System.currentTimeMillis();
       if((BluetoothManger.mLockOpenedtime>0)&&(cur_time - BluetoothManger.mLockOpenedtime)>180000){
           soundWarn();
       }


//    Dialog dialog = new Dialog(BluetoothSetActivity.this, R.style.dialog);
//    dialog.setContentView(R.layout.activity_door_warn);
//
//
//    TextView warnTv=(TextView) dialog.findViewById(R.id.warn_closewarn_tx);
//    warnTv.setText("关锁提醒：       ");
//    TextView batteryTv=(TextView) dialog.findViewById(R.id.warn_battery_tx);
//    Button closeBtn=(Button) dialog.findViewById(R.id.warn_close_Btn);
//    closeBtn.setOnClickListener(new View.OnClickListener() {
//        @Override
//        public void onClick(View v) {
//            Toast.makeText(BluetoothSetActivity.this,"关锁",Toast.LENGTH_LONG).show();
//        }
//    });
//    dialog.setCancelable(false);
//    dialog.show();
    }

    public  void  getBluetoothLock(String status){
        BaseSubscribe.getBluetoothLock(BluetoothSetActivity.this, GlobalVaries.curBlueMac,status,"授权开锁",Integer.toString( GlobalVaries.curBattery.intValue()), new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                //重新刷新
                Toast.makeText(BluetoothSetActivity.this, "getBluetoothLock成功！" , Toast.LENGTH_LONG).show();

            }

            @Override
            public void onFault(String errorMsg) {
                Toast.makeText(BluetoothSetActivity.this, "getBluetoothLock失败！" + errorMsg, Toast.LENGTH_LONG).show();
            }

        }));
    }


    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            myhandleMessage(msg);
        }
    };

    //private boolean mneedreconnect =true;

    private void myhandleMessage(Message msg) {
        try {
            //syj     startCaptureTimeCount();
            Log.e("syj","msg is "+Integer.toString(msg.what));
            switch (msg.what) {
//GATT连接上
                case BluetoothManger.ACTION_GATT_CONNECTED:
                    //   mneedreconnect=false;
                    dismissprogressDialog();
                    Log.e("syj","update1:"+Double.toString(GlobalVaries.curBattery));
                    GlobalVaries.UpdateWarnFlag=true;
                    alertBuilder = null;
                    ConnectCounterFlag=false;
                    ConnectCounter =0;
                    BluetoothManger.reconnectFlag=false;
                    getBluetoothLock("1");//发送开锁记录0622
                    showWarnDialog(Integer.toString(BluetoothManger.counter),GlobalVaries.curBattery);
                    UpdateThread myThread = new UpdateThread();
                    new Thread(myThread).start();
                    break;
                //GATT断开连接
                case  BluetoothManger.ACTION_GATT_DISCONNECTED:

                    GlobalVaries.UpdateWarnFlag=false;
                    BluetoothManger.resetBluetooth();

                    if(BluetoothManger.reconnectFlag==false) {
                        dismissprogressDialog();
                        ConnectCounter = 0;
                        ConnectCounterFlag = false;
                        Log.e("syj","stop Aand not reconnect");
                    }
                    //根据实际需要 决定是否重连
                    Log.e( BluetoothManger.TAG, "Lock DisConnected." + hashCode());


                    break;

                case  BluetoothManger.ACTION_GATT_SERVICES_DISCOVERED: //发现了对应的服务
                    // Log.e(TAG,"Lock GATT_SERVICES_DISCOVERED."+hashCode());//add by 20221026
                    //发现服务..mWorkModel:0=开锁，1=查询参数，2=设置参数
                    if ( BluetoothManger.mWorkModel == 0) {
                        if ( BluetoothManger.mLockIsOpened ||  BluetoothManger.mIsDoCheckLockState)
                            handler.sendEmptyMessageDelayed(4, 500);//验封.检测锁状态
                        else
                            handler.sendEmptyMessageDelayed(0, 500);//解封，开锁
                    }


                    break;
                case  BluetoothManger.ACTION_BLE_REAL_DATA:
                    byte[]values =(byte[])msg.obj;
                    BluetoothManger.TMPL_processData(values);
                    Log.e(BluetoothManger.TAG,"state_changed");

                    break;
//                case BluetoothAdapter.ACTION_STATE_CHANGED:
//                    // Log.e(LockManageActivity.class.getSimpleName(),"state_changed");
//                    break;
                case 0://发送开锁指令
                    BluetoothManger.mIsDoCheckLockState = false;

                    BluetoothManger.TMPL_ReadLockUTCTime();

                    break;
                case BluetoothManger.DISMISS_PROGRESS_DIALOG:
//                    GlobalVaries.UpdateWarnFlag=false;
//                    BluetoothManger.resetBluetooth();
                    dismissprogressDialog();
                    break;
////                case 1://获取电量
//                    byte[] batteryBytes = {0x02, 0x01, 0x01, 0x01, token[0], token[1], token[2], token[3], 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//                    boolean result = writeCharacteristic_GuaSuo(batteryBytes);
//                    Log.e(TAG, "Lock 发送获取电量指令=" + result);
//                    break;
////                case 2://开锁
//                   byte[] sendDataBytes = new byte[]{ 0x05, 0x01, 0x06,password[0], password[1], password[2], password[3], password[4], password[5], token[0], token[1], token[2], token[3], 0x00, 0x00, 0x00};
//                    result = writeCharacteristic_GuaSuo(sendDataBytes);
//                    Log.e(TAG, "Lock 发送开锁指令=" + result);
//                    break;
                case 3://获取锁状态

//                    byte[] sendDataBytes1 = new byte[]{0x05, 0x0E, 0x01, 0X01, token[0], token[1], token[2], token[3], 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//                    result = writeCharacteristic_GuaSuo(sendDataBytes1);
                    Log.e(BluetoothManger.TAG, "Lock 发送获取锁状态指令=" );
                    break;
                case 4://发送施封指令。。航鸿达
                    BluetoothManger.TMPL_SendGetLockStateCMD();
                    Log.e( BluetoothManger.TAG, "Lock 发送获取锁状态指令,result=");
                    break;
                case  BluetoothManger.UPDATE_WARNDIALOG:
//                    BluetoothManger.TMPL_SendGetLockStateCMD();
//                    Log.e( BluetoothManger.TAG, "Lock 发送获取锁状态指令2,result=");
                    BluetoothManger.counter++;
             //       GlobalVaries.UpdateWarnFlag=true;
                    Log.e("syj","update2:"+Double.toString(GlobalVaries.curBattery));

                    showWarnDialog(Integer.toString( BluetoothManger.counter), GlobalVaries.curBattery);




                    break;
                case  BluetoothManger.CLOSE_LOCK:
                    alertDialog.dismiss();
                    GlobalVaries.UpdateWarnFlag = false;
                    //syj  关锁之后立刻断开连接
                    BluetoothManger.disconnectLock();
                    if(player!=null)
                    {
                        if(player.isLooping()) {
                            player.setLooping(false);
                        }
                        if(player.isPlaying()) {
                            player.stop();
                        }
                        player.release(); // 释放资源
                        player =null;
                    }
                case BluetoothManger.UPDATE_STATE:
                    handler.postDelayed( new Runnable() {
                        @Override
                        public void run() {
                            Log.e(BluetoothManger.TAG,"RRRRRRR");
                            BluetoothManger.TMPL_SendGetLockStateCMD();

                        }
                    }, 1000);
                    break;
                case BluetoothManger.RECONNECT:
                    Log.e("syj","reconnect cunter :"+Integer.toString(ConnectCounter));
                    if(ConnectCounter==120){
                        BluetoothManger.reconnectFlag=false;
                        ConnectCounter=0;
                        ConnectCounterFlag=false;
                        BluetoothManger.disconnectLock();
                        dismissprogressDialog();

                        Toast.makeText(BluetoothSetActivity.this,"连接设备"+GlobalVaries.curBlueMac+"失败，请检查！",Toast.LENGTH_LONG).show();
                    }else if((ConnectCounter==60)||(ConnectCounter==61)) {

                   //     BluetoothManger.connectLock(BluetoothSetActivity.this,GlobalVaries.curBlueMac,false);
                        BluetoothManger.reconnectFlag=true;
                        BluetoothManger.disconnectLock();


                    }else if((ConnectCounter==70)||(ConnectCounter==71)){
                        startBluetooth();
                        dismissprogressDialog();
                        startShowProgressDialog("正在重新连接蓝牙设备！");


                    }
//                    else if((ConnectCounter==30)||(ConnectCounter==31)){
//                        BluetoothManger.reconnectFlag=true;
//                        BluetoothManger.disconnectLock();
//
//
//                    }

                    break;
                case BluetoothManger.SEND_OPEN_RECORD:
                    recordOpenLock(Integer.toString(cur_commonid));
                    getBluetoothLock("2");//syj 发送关锁记录0622
                    break;

            }
        } catch (Exception ee) {
            //ee.printStackTrace();
            Log.e( BluetoothManger.TAG, ee.getMessage());
            // syj showMessage(ee.getMessage());
        }
    }


    class UpdateThread implements Runnable {
        @Override
        public void run() {
            while (GlobalVaries.UpdateWarnFlag) {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = BluetoothManger.UPDATE_WARNDIALOG;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }


        }

    }
    class ConnectThread implements Runnable {
        @Override
        public void run() {
            while (ConnectCounterFlag) {
                try {
                    Log.e("syj","recounter "+Integer.toString(ConnectCounter));
                    Thread.sleep(1000);
                    BluetoothManger.reconnectFlag=true;
                    if(ConnectCounter==120)
                    {
                        BluetoothManger.reconnectFlag=false;
                        ConnectCounterFlag=false;
                        Message msg = new Message();
                        msg.what = BluetoothManger.RECONNECT;
                        handler.sendMessage(msg);
                    }
                    else if((ConnectCounter==60)){

                        Message msg = new Message();
                        msg.what = BluetoothManger.RECONNECT;
                        handler.sendMessage(msg);
                        ConnectCounter++;
                    }else  if((ConnectCounter==70)){

                        Message msg = new Message();
                        msg.what = BluetoothManger.RECONNECT;
                        handler.sendMessage(msg);
                        ConnectCounter++;
                    }else{
                        ConnectCounter++;
                    }
//                    Message msg = new Message();
//                    msg.what = BluetoothManger.UPDATE_WARNDIALOG;
//                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }


        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults){
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 有权限没有通过
        boolean hasPermissionDismiss = false;
        int i = 0;
        if(1001 == requestCode){

            for( i = 0; i < grantResults.length; i++){
                if(grantResults[i] == -1){
                    hasPermissionDismiss = true;
                    break;
                }
            }
        }
        if(hasPermissionDismiss){
            // 有权限未通过的处理
		Toast.makeText(BluetoothSetActivity.this,permissions[i]+"未通过",Toast.LENGTH_LONG).show();
        } else {
            //权限全部通过的处理
		Log.e("syj","权限全部通过");
        }
    }
    private MediaPlayer player = new MediaPlayer();
public void soundWarn(){

    if((player==null)||(player.isPlaying()==false)) {
        player = new MediaPlayer();
        AssetManager assetManager = getResources().getAssets();
        try {
            AssetFileDescriptor fileDescriptor = assetManager.openFd("请关锁.mp3");//加载MP3
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());
            player.setLooping(true);
            player.prepare();
            player.start();//开始
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}



//       mBluetoothGatt.disconnect();
//                    mBluetoothGatt.close();






}